/**
 * Thread
 *
 * Functions for easy creation of new threads
 *
 * @author Jasper Nevens <jasper@nevensit.be>
 * @date    19/02/11
 */

#include <pthread.h>
#include <iostream>
#include "thread.h"

using namespace std;

extern "C"
{
    // this C function will be used to receive the thread and pass it back to the Thread instance
    void* thread_catch(void* arg) {
        Thread* t = static_cast<Thread*>(arg);
        t->execute();
        return 0;
    }
}


/**
 * Thread::start();
 *
 * method which starts the new thread
 *
 * @author Jasper Nevens <jappe@nevensit.be>
 * @date    19/02/11
 */
void Thread::start() {
    pthread_create(&handle, 0, thread_catch, this);
}

/**
 * Thread::execute();
 *
 * code which will be run on the new thread, this function should be overwritten
 *
 * @author Jasper Nevens <jappe@nevensit.be>
 * @date    19/02/11
 */
void Thread::execute() {
    cout << "Thread:Hello From a new Thread!" << endl;
}
/**
 * Thread::wait_for_exit();
 *
 * wait until this thread has finished executing
 *
 * @author Jasper Nevens <jappe@nevensit.be>
 * @date    19/02/11
 */
void Thread::wait_for_exit() {
    pthread_join(handle, NULL);
}

/** Probeer de lock op object te krijgen
 * 
 * print foutmelding als het niet gaat
 * @param __mutex
 */
int mutex_lock(pthread_mutex_t* __mutex){
    int r = pthread_mutex_trylock(__mutex);

    if(r != 0)
    {
        cout << "Mutex_Lock Mislukt!: " << r << endl;
        return pthread_mutex_lock(__mutex);
    }
    else
        return r;
}

int mutex_unlock(pthread_mutex_t* __mutex){
    return pthread_mutex_unlock(__mutex);
}
